package com.ctsi.organise.service;

import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.id.UUIDGenerator;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.exception.ExceptionFactory;
import com.ctsi.framework.mybatis.support.MybatisGenericDao;
import com.ctsi.organise.entity.UserLoginEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * UserLoginEntity Service 类
 *
 * @author zhangjw
 * @description UserLoginEntity
 * @created Sun Nov 11 17:47:38 CST 2018
 */

@Repository
public class UserLoginEntityManager {
    private static final Logger logger = LoggerFactory.getLogger(UserLoginEntityManager.class);
    @Autowired
    private MybatisGenericDao dao;
    @Autowired
    private ExceptionFactory exceptionFactory;
    /**
     * 是否允许一个人多个账号，默认是false
     */
    private boolean isMany = false;

    /**
     * 添加
     */
    public void insertUserLoginEntity(UserLoginEntity userLoginEntity) {
        if (UtilValidate.isEmpty(userLoginEntity.getId()))
            userLoginEntity.setId(UUIDGenerator.getId());
        logger.debug("insert {}", userLoginEntity);
        dao.insert(userLoginEntity);
    }
/*
*修改密码
* */
public int updateLoginPsw(UserLoginEntity userLoginEntity){
    logger.debug("updateLoginPsw {}", userLoginEntity);
    return dao.update(UserLoginEntity.class.getName()+".updateLoginPsw",userLoginEntity);
}
    /**
     * 动态更新
     */
    public int updateUserLoginEntityByPKSelective(UserLoginEntity userLoginEntity) {
        logger.debug("updateByPrimaryKeySelective {}", userLoginEntity);
        return dao.update(UserLoginEntity.class.getName() + ".updateByPrimaryKeySelective", userLoginEntity);
    }

    /**
     * 更新
     */
    public int updateUserLoginEntity(UserLoginEntity userLoginEntity) {
        logger.debug("update {}", userLoginEntity);
        return dao.update(userLoginEntity);
    }


    public UserLoginEntity editUserLoginEntityById(String id) {
        if (UtilValidate.isEmpty(id))
            return null;
        logger.debug("editById {}", id);
        return (UserLoginEntity) dao.queryForObject(UserLoginEntity.class.getName() + ".edit", id);
    }

    /**
     * 根据ID查找 UserLoginEntity对象
     */
    public UserLoginEntity findUserLoginEntityById(String id) {
        if (UtilValidate.isEmpty(id))
            return null;
        logger.debug("findById {}", id);
        return dao.get(UserLoginEntity.class, id);
    }

    /**
     * 删除UserLoginEntity对象
     */
    public int removeUserLoginEntity(String id) {
        if (UtilValidate.isNotEmpty(id))
            return dao.delete(UserLoginEntity.class.getName() + ".delete", id);
        //return dao.remove(id);
        return 0;
    }

    /**
     * 详细页查询
     */
    public UserLoginEntity findByDetail(String id) {
        return (UserLoginEntity) dao.queryForObject(UserLoginEntity.class.getName() + ".findByDetail", id);
    }

    /**
     * 多条件查询结果
     */
    public Page<UserLoginEntity> findByMulitCondition(Map<String, Object> param, int start, int pageSize) {
        logger.debug("findByMulitCondition {}", param);
        if (pageSize < 0 || pageSize > 2000)
            pageSize = Page.DEFAULT_PAGE_SIZE;
        if (start != -1)
            return dao.queryPage(UserLoginEntity.class.getName() + ".selectMulitCondition", param, start, pageSize);
        else {
            throw new RuntimeException("参数不正确 !!");
        }
    }

    /**
     * 多条件查询结果不分页
     */
    public List<UserLoginEntity> find(Map<String, Object> map) {
        logger.debug("find {}", map);
        return (List<UserLoginEntity>) dao.queryForList(UserLoginEntity.class.getName() + ".selectByMap", map);
    }

    /**
     * 根据用户登录名找到该用户
     *
     * @param loginName
     * @return
     */
    public UserLoginEntity findUserLoginByLoginName(String loginName) {
        return (UserLoginEntity) dao.queryForObject(UserLoginEntity.class.getName() + ".selectUserLoginByLoginName", loginName);
    }

    /**
     * 验证用户账户的唯一性
     *
     * @param user
     * @return
     */
    public boolean validateUser(UserLoginEntity user) {
        if (isMany) {
            return true;
        } else {
            String partyId = user.getPartyId();
            Map<String, Object> params = new HashMap<>();
            params.put("partyId", partyId);
            long count = (long) dao.queryForObject(UserLoginEntity.class.getName() + ".selectMulitCondition_count", params);
            if (count > 0) {
                return false;
            } else {
                return true;
            }
        }
    }


    /**
     * 添加登陆用户
     *
     * @param user
     * @param publishEvent
     */
    public void addUserLogin(UserLoginEntity user, boolean publishEvent) {
        if (!validateUser(user)) {
            logger.warn("User had login account already! partyId is {}", user.getPartyId());
            exceptionFactory.throwDefinedException("30002");
        }
        String loginName = user.getLoginName();
        UserLoginEntity us = this.findUserLoginByLoginName(loginName);
        if (us != null) {
            exceptionFactory.throwDefinedException("30003", loginName);
        }
        user.setId(UUIDGenerator.getId());
        user.setChangePwd(0);
        user.setCreatePwdDate(System.currentTimeMillis());
        this.insertUserLoginEntity(user);
    }


}
